package com.party.admin.web.controller.gatherForm;

import com.google.common.collect.Maps;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.biz.gatherForm.GatherFormInfoBizService;
import com.party.admin.utils.excel.ExportExcel;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherFormInfo;
import com.party.core.model.gatherForm.GatherFormOption;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormOptionService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.member.IMemberGroupService;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("gatherForm/form")
public class GatherFormController {

    @Autowired
    private IGatherFormService gatherFormService;
    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private IGatherProjectService gatherProjectService;
    @Autowired
    private IGatherFormOptionService gatherFormOptionService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private GatherFormInfoBizService gatherFormInfoBizService;
    @Autowired
    private ExcelExportService excelExportService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 表单收集信息列表
     *
     * @param projectId
     * @param commonInput
     * @param page
     * @return
     * @throws Exception
     */
    @RequestMapping("list")
    public ModelAndView list(String projectId, CommonInput commonInput, Page page) throws Exception {
        page.setLimit(30);
        Map<String, Object> params = Maps.newHashMap();
        params.put("projectId", projectId);
        List<Map<String, Object>> gatherForms = gatherFormInfoService.webListPage(params, page);

		/*for (Map<String, Object> input : gatherForms) {
			GatherFormInfoOutput output = new GatherFormInfoOutput();
			String maxIndex = input.get("maxIndex") != null ? input.get("maxIndex").toString() : "";
			output.setMaxIndex(maxIndex);
			String fieldValue = input.get("fieldValue") != null ? input.get("fieldValue").toString() : "";
			String [] result = new String[fields.size()];
			for (int i = 0; i < fieldValue.split("maxIndex").length; i++) {
				result[i] = fieldValue.split("maxIndex")[i];
			}
			output.setFieldValues(result);
			if (null != input.get("createBy") && StringUtils.isNotEmpty(input.get("createBy").toString())) {
				Member member = memberService.get(input.get("createBy").toString());
				output.setMember(member);
			}
			output.setCreateDate((Date) input.get("createDate"));
			outputs.add(output);
		}*/
        ModelAndView mv = new ModelAndView("gatherForm/formInfoList");
        mv.addObject("input", commonInput);
        mv.addObject("page", page);

        List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
        mv.addObject("fields", fields);

        mv.addObject("formInfos", gatherForms);
        GatherProject gatherProject = gatherProjectService.get(projectId);
        mv.addObject("project", gatherProject);
        return mv;
    }

    /**
     * 表单信息详情
     *
     * @param maxIndex
     * @param projectId
     * @return
     */
    @ResponseBody
    @RequestMapping("/formInfo")
    public ModelAndView formInfo(String maxIndex, String projectId) {
        ModelAndView mv = new ModelAndView("gatherForm/formInfo");
        List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));

        //查询来源
        String resourceId = null;
        for (GatherForm gf : fields) {
            if (Constant.FIELD_RESOURCE.equals(gf.getCategory())) {
                resourceId = gf.getId();
            }
        }
        mv.addObject("fields", fields);
        GatherFormInfo t = new GatherFormInfo();
        t.setProjectId(projectId);
        t.setMaxIndex(Integer.valueOf(maxIndex));
        List<GatherFormInfo> infos = gatherFormInfoService.list(t);

        //特殊处理来源
        if (null != resourceId) {
            for (GatherFormInfo gi : infos) {
                if (gi.getFieldId().equals(resourceId)) {
                    MemberGroup member = memberGroupService.get(gi.getFieldValue());
                    if (null != member) {
                        gi.setFieldValue(member.getRealname());
                    }
                }
            }
        }
        mv.addObject("infos", infos);
        return mv;
    }

    /**
     * 删除表单字段
     *
     * @param projectId
     * @param maxIndex
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String projectId, String maxIndex) {
        try {
            if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(maxIndex)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.setSuccess(false);
                return ajaxResult;
            }
            gatherFormInfoService.deleteByProjectId(projectId, maxIndex);

            GatherProject gatherProject = gatherProjectService.get(projectId);
            gatherProject.setQuantity(gatherProject.getQuantity() - 1);
            gatherProjectService.update(gatherProject);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除数据异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除数据异常");
        }
    }

    /**
     * 删除单个字段
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteField")
    public AjaxResult deleteField(String id) {
        gatherFormService.delete(id);
        return AjaxResult.success();
    }

    /**
     * 删除单个选项
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteOption")
    public AjaxResult deleteOption(String id) {
        gatherFormOptionService.delete(id);
        return AjaxResult.success();
    }

    /**
     * 导出表单收集信息
     *
     * @param projectId
     * @param commonInput
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("exportFormInfo")
    public AjaxResult exportFormInfo(String projectId, CommonInput commonInput) {
        try {
            String fileName = "表单收集.xlsx";
            GatherProject gatherProject = gatherProjectService.get(projectId);
            Map<String, Object> params = CommonInput.appendParams(commonInput);
            params.put("projectId", projectId);
            List<Map<String, Object>> gatherForms = gatherFormInfoService.webListPage(params, null);
            List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
            SXSSFWorkbook workbook = gatherFormInfoBizService.exportExcel(gatherForms, fields, gatherProject.getShowResource());
            String allPath = excelExportService.getExcelPath(fileName, "gatherForm", new ExportExcel(), workbook);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("表单信息导出异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    /**
     * @param projectId 项目id
     * @param targetId  报名id
     * @param isNew     是否第一次 第一次就加载表单所有字段
     * @return
     */
    @ResponseBody
    @RequestMapping("getFormInfoByTargetId")
    public AjaxResult getFormInfoByTargetId(String projectId, String targetId, boolean isNew) {
        if (StringUtils.isEmpty(targetId) || StringUtils.isEmpty(projectId)) {
            return AjaxResult.error("项目id或者业务id不能为空");
        }
        try {
            Map<String, Object> result = Maps.newHashMap();
            if (isNew) {
                List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
                result.put("fields", fields);
            }
            GatherFormInfo t = new GatherFormInfo();
            t.setProjectId(projectId);
            t.setTargetId(targetId);
            List<GatherFormInfo> infos = gatherFormInfoService.list(t);
            result.put("infos", infos);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取业务id对应的数据异常", e);
            return AjaxResult.error("获取数据异常");
        }
    }


    /**
     * 自定义信息收集数据维护
     *
     * @param gdProjectId 项目id
     * @return
     */
    @ResponseBody
    @RequestMapping("gatFormInfoDataMaintain")
    public AjaxResult gatFormInfoDataMaintain(String gdProjectId) {

        if (StringUtils.isEmpty(gdProjectId)) {
            return AjaxResult.error("项目id不能为空");
        }
        GatherProject gatherProject = gatherProjectService.get(gdProjectId);
        if (null == gatherProject) {
            return AjaxResult.error("项目不存在");
        }

        try {
            GatherForm gatherForm = new GatherForm();
            gatherForm.setTitle("信息分类");
            gatherForm.setType("select");
            gatherForm.setRequired("true");
            gatherForm.setProjectId(gdProjectId);
            gatherForm.setSort(0);
            gatherForm.setMaxIndex(1);
            gatherForm.setCreateBy(gatherProject.getCreateBy());
            gatherForm.setUpdateBy(gatherProject.getCreateBy());
            gatherForm.setCategory("");
            gatherFormService.insert(gatherForm);

            String[] ops = {"联系合作", "产品建议", "问题反馈", "其他"};

            for (int i = 0; ops.length > i; i++) {
                GatherFormOption gatherFormOption = new GatherFormOption();
                gatherFormOption.setFieldId(gatherForm.getId());
                gatherFormOption.setCreateBy(gatherProject.getCreateBy());
                gatherFormOption.setName(ops[i]);
                gatherFormOption.setSort(i);
                gatherFormOptionService.insert(gatherFormOption);
            }

            GatherForm fieldRealname = gatherFormService.findByCategory(new GatherForm(gatherProject.getId(), "FIELD_REALNAME"));
            List<GatherFormInfo> formInfoByFieldAndProjectId = gatherFormInfoService.getFormInfoByFieldAndProjectId(gatherProject.getId(), fieldRealname.getId());

            for (GatherFormInfo gfi : formInfoByFieldAndProjectId) {
                GatherFormInfo gatherFormInfo = new GatherFormInfo();
                gatherFormInfo.setProjectId(gatherProject.getId());
                gatherFormInfo.setFieldValue("其他");
                gatherFormInfo.setMaxIndex(gfi.getMaxIndex());
                gatherFormInfo.setFieldId(gatherForm.getId());
                gatherFormInfo.setSort(gatherForm.getSort());
                gatherFormInfo.setCreateBy(gatherForm.getCreateBy());

                gatherFormInfoService.insert(gatherFormInfo);
            }


            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("自定义信息收集数据维护异常", e);
            return AjaxResult.error("自定义信息收集数据维护异常");
        }
    }
}
